﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using FastJSON;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using DingTida.Models;
using RouteAttribute = Microsoft.AspNetCore.Components.RouteAttribute;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Data.SqlClient;
using Microsoft.IdentityModel.Protocols;
using System.Data;
using System.IO;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.Internal;
using Microsoft.AspNetCore.Hosting;
using System.Globalization;
using DingTida.BLL;
using DingTida.IBLL;
using DingTida.Comnon;


namespace DingTida.Controllers
{
    [Route("api/[controller]")]
   // [ApiController]
    public class ApproveController : ControllerBase
    {

        public string access_token = "";
        public EasyStarContext db;
        public OapiUserGetuserinfoResponse rsp = null;
        public string name;
        public IMemoryCache Cache;
        private IWebHostEnvironment _webHostEnvironment;
        public IWorkFlowInstance wfi;
        public IMsg msg;
        public ApproveController(EasyStarContext _db, IMemoryCache _cache, IWebHostEnvironment webHostEnvironment, IWorkFlowInstance _wfi,IMsg _msg)
        {
            this.db = _db;
            this.Cache = _cache;
            this._webHostEnvironment = webHostEnvironment;
            this.wfi = _wfi;
            this.msg = _msg;
        }
        [HttpGet]

        #region  待我核签列表
        public IActionResult WaitMeApproveList(string staffid)
        {


            var u2 = db.CustomDictionary.Where(c => c.Ckey == "car").FirstOrDefault();
            var ApList = db.WorkFlowsInstance.Where(c => c.ApproveUser == staffid && c.IsCurrentStep == true).ToList();
            if (ApList.Count > 0)
            {
                var id = ApList.FirstOrDefault().WorkFlowId;



                List<Approve> Aplst = new List<Approve>();
                int i = ApList.Count();
                for (int a = 0; a < i; a++)
                {
                    var ap = new Approve();
                    ap.id = ApList[a].Id;

                    var cnt = db.WorkFlows.Where(c => c.FlowId == ApList[a].WorkFlowId).FirstOrDefault();
                    ap.content = cnt.FlowContent;
                    ap.type = cnt.Type;
                    ap.reson = cnt.Reason;
                    ap.caru = u2.Value;

                    Aplst.Add(ap);

                }
                // db.SaveChanges();
                return Ok(new {msg="数据返回成功",data= Aplst });
            }
            else {

                return Ok(new { msg="暂时没有待审批的内容"});
            }


        }
        #endregion
        [HttpGet]

        #region  待我核签列表
        public IActionResult WaitApproveList(int page, int limit)
        {

            var staffid = HttpContext.Session.GetString("username");
            var u2 = db.CustomDictionary.Where(c => c.Ckey == "car").FirstOrDefault();
            var ApList = db.WorkFlowsInstance.Where(c => c.ApproveUser == staffid && c.IsCurrentStep == true).ToList();
            if (ApList.Count > 0)
            {
                var id = ApList.FirstOrDefault().WorkFlowId;



                List<Approve> Aplst = new List<Approve>();
                int i = ApList.Count();
                for (int a = 0; a < i; a++)
                {
                    var ap = new Approve();
                    ap.id = ApList[a].Id;

                    var cnt = db.WorkFlows.Where(c => c.FlowId == ApList[a].WorkFlowId).FirstOrDefault();
                    ap.content = cnt.FlowContent;
                    ap.type = cnt.Type;
                    ap.reson = cnt.Reason;
                    ap.caru = u2.Value;

                    Aplst.Add(ap);



                }


                // db.SaveChanges();
                return Ok(new { msg = "数据返回成功",
                    code = 0,
                  
                    count = Aplst.Count,
                    data = Aplst.OrderBy(c => c.id).Skip((page - 1) * (limit)).Take(limit).ToList()
            });
            }
            else
            {

                return Ok(new { msg = "暂时没有待审批的内容" });
            }


        }
        #endregion
        [HttpGet]
        public IActionResult Reject(string id) 
        {
            var oo = int.Parse(id);

            var wfi = db.WorkFlowsInstance.Where(c => c.Id == oo).FirstOrDefault();
            wfi.Refused = true;
            var ls = db.WorkFlowsInstance.Where(c => c.WorkFlowId == wfi.WorkFlowId && c.FlowStep == wfi.FlowStep).ToList();
            foreach (var it in ls)
            {
                it.IsCurrentStep = false;
                db.SaveChanges();
            }

            var wf = db.WorkFlows.Where(c => c.FlowId == wfi.WorkFlowId).FirstOrDefault();
            wf.FlowContent += "被拒绝";
            wf.States = "拒绝";
            if (wf.Type == "调休假")
            {
                var other = db.WorkFlows.Where(c => c.Id == wf.OtherId).FirstOrDefault();
                other.IsAdjust = false;
            
            }


            wf.IsComplete = true;
            msg.SendMsg("您的申请已经被拒绝"+wf.FlowContent,wf.Staffid);

            db.SaveChanges();

            return Ok(new { msg = "ok" });
        
        }

        [HttpGet]
        public IActionResult back(string id)
        {
           // var oo = int.Parse(id);

          //  var wfi = db.WorkFlowsInstance.Where(c => c.WorkFlowId == id).FirstOrDefault();
            var wf = db.WorkFlows.Where(c => c.FlowId == id).FirstOrDefault();
            if (wf.IsComplete != true)
            {
                var ls = db.WorkFlowsInstance.Where(c => c.WorkFlowId ==id).ToList();
                foreach (var it in ls)
                {
                    it.IsCurrentStep = false;
                   // it.Refused = true;
                    db.WorkFlowsInstance.Update(it);
                    db.SaveChanges();
                }

                if (wf.Type == "调休假")
                {
                    var other = db.WorkFlows.Where(c => c.Id == wf.OtherId).FirstOrDefault();
                    other.IsAdjust = false;

                }

                wf.FlowContent += "用户撤回";
                wf.States = "撤回";
                wf.IsComplete = true;
                msg.SendMsg("您的申请已经成功撤回" + wf.FlowContent, wf.Staffid);
                db.WorkFlows.Update(wf);
                db.SaveChanges();
                return Ok(new { msg = "撤回成功" });
            }
            return Ok(new { msg = "已经完成的流程不可撤回" });


        }

        [HttpGet]
        #region 同意
        public IActionResult Approved(string id)
        {
            var oo = int.Parse(id);

            var wfi = db.WorkFlowsInstance.Where(c => c.Id == oo).FirstOrDefault();
            var wf = db.WorkFlows.Where(c => c.FlowId == wfi.WorkFlowId).FirstOrDefault();

            if (wfi != null)
            {
                //本步集合
                var wfis = db.WorkFlowsInstance.Where(c => c.WorkFlowId == wfi.WorkFlowId.ToString() && c.FlowStep == wfi.FlowStep).ToList();
                //下一步集合
                var wfii = db.WorkFlowsInstance.Where(c => c.WorkFlowId == wfi.WorkFlowId.ToString() && c.FlowStep == wfi.FlowStep + 1).ToList();
                if (wfii.Count > 0)
                {
                    // wfi.IsCurrentStep = false;
                    wf.States = "进行中";
                    //流转到下一步

                    #region 流转到下一步 ,更新本步为假,下一步为真
                    foreach (var it in wfis)
                    {

                        // var itm = db.WorkFlowsInstance.Where(c => c.Id == it.Id).FirstOrDefault();
                        it.IsCurrentStep = false;
                        db.WorkFlowsInstance.Update(it);

                        db.SaveChanges();

                    }

                    wfi.IsCurrentStep = false;
                    wfi.ApproveDate = System.DateTime.Now;
                    wfi.Approved = true;


                    foreach (var it in wfii)
                    {

                        //  var it = db.WorkFlowsInstance.Where(c => c.Id == it.Id).FirstOrDefault();
                        it.IsCurrentStep = true;
                   
                         msg.SendMsg("钉钉提醒您，泰德小程序OA内有一条待核签事项" + wf.FlowContent ,it.ApproveUser);
                        db.WorkFlowsInstance.Update(it);
                        db.SaveChanges();

                    } 
                    #endregion



                }
                else {
                    var typ = wf.Type;
                    if (wfi.LastStep == true)
                    {
                        if (wf.Type == "加班")
                        {

                            wfi.ApproveDate = System.DateTime.Now;

                            foreach (var it in wfis)
                            {
                                it.IsCurrentStep = false;

                                db.WorkFlowsInstance.Update(it);

                                db.SaveChanges();


                            }



                            var xb = timeHelper.GetMin((DateTime)wf.Enddate);
                            var sb = timeHelper.GetMin((DateTime)wf.Begindate);
                            var user = db.EmEmpData.Where(c => c.EmpNo == wf.Staffid).FirstOrDefault();
                            KmJiaBan ot = new KmJiaBan();
                            ot.EmpId = user.EmpId;
                            ot.Fdate = (DateTime)wf.Begindate.Value.Date;
                            ot.SbTime = (short)sb;
                            ot.XbTime = (short)xb;
                            ot.Flag = 0;
                            ot.XxSj = 0;
                            ot.Hours = (xb - sb) / 60;
                            ot.UserName = "JHS";
                            ot.UpdateTime = System.DateTime.Now;
                            ot.Jbtype = wf.Remark;
                            ot.Note = wf.Reason;
                            wfi.IsCurrentStep = false;
                            wf.States = "完成";
                            msg.SendMsg("您的申请已经被批准" + wf.FlowContent, wf.Staffid);
                            wf.IsComplete = true;


                            db.WorkFlows.Update(wf);
                            db.KmJiaBan.Add(ot);
                            db.SaveChanges();

                        }

                        else if (typ == "出差" || typ == "事假" || typ == "病假" || typ == "丧假" || typ == "产假" || typ == "婚假" || typ == "看护假" || typ == "工伤假")
                        {

                            var emp = db.EmEmpData.Where(c => c.EmpNo == wf.Staffid).FirstOrDefault().EmpId;
                            var qjtype = db.UserField.Where(c => c.TblName == "KmResult" && c.FieldCn == typ).FirstOrDefault().FieldName;
                            var le = new KmQqDj();
                            le.EmpId = emp;
                            le.QqTime0 = (DateTime)wf.Begindate;
                            le.QqTime1 = (DateTime)wf.Enddate;
                            le.Hours = (decimal)wf.Hour;
                            le.Years = wf.Year;
                            le.Days = (decimal)wf.Day;
                            le.UserName = "Ding";
                            le.Note = wf.Reason;
                            le.QqType = qjtype;

                            db.KmQqDj.Add(le);
                            wfi.IsCurrentStep = false;
                            wf.States = "完成";
                            msg.SendMsg("您的申请已经被批准" + wf.FlowContent, wf.Staffid);
                            wf.IsComplete = true;


                            db.SaveChanges();

                        }
                        else if (typ == "年休假")
                        {
                            var emp = db.EmEmpData.Where(c => c.EmpNo == wf.Staffid).FirstOrDefault().EmpId;
                            var qjtype = db.UserField.Where(c => c.TblName == "KmResult" && c.FieldCn == typ).FirstOrDefault().FieldName;
                            var le = new KmQqDj();
                            le.EmpId = emp;
                            le.QqTime0 = (DateTime)wf.Begindate;
                            le.QqTime1 = (DateTime)wf.Enddate;
                            le.Hours = (decimal)wf.Hour;
                            le.Years = wf.Year;
                            le.Days = (decimal)wf.Day;
                            le.UserName = "Ding";
                            le.QqType = qjtype;
                            le.Note = wf.Reason;
                            wfi.IsCurrentStep = false;
                            wf.States = "完成";
                            msg.SendMsg("您的申请已经被批准" + wf.FlowContent, wf.Staffid);
                            wf.IsComplete = true;
                            db.KmQqDj.Add(le);
                            db.SaveChanges();


                        }
                        else if (typ == "调休假")
                        {

                            var emp = db.EmEmpData.Where(c => c.EmpNo == wf.Staffid).FirstOrDefault().EmpId;
                            var qjtype = db.UserField.Where(c => c.TblName == "KmResult" && c.FieldCn == typ).FirstOrDefault().FieldName;
                            var le = new KmQqDj();
                            le.EmpId = emp;
                            le.QqTime0 = (DateTime)wf.Begindate;
                            le.QqTime1 = (DateTime)wf.Enddate;
                            le.Hours = (decimal)wf.Hour;
                            le.Years = wf.Year;
                            le.Days = (decimal)wf.Day;
                            le.UserName = "Ding";
                            le.Note = wf.Reason;
                            wfi.IsCurrentStep = false;
                            wf.States = "完成";
                            msg.SendMsg("您的申请已经被批准" + wf.FlowContent, wf.Staffid);
                            wf.IsComplete = true;
                            db.KmQqDj.Add(le);
                            db.SaveChanges();
                        }
                   



                    }


                }



            }

            return Ok(new { msg = "ok" });
                
        }
        #endregion

        [HttpGet]
        public IActionResult MyApply(string empid)
        {
            var wfs = db.WorkFlows.Where(c => c.Staffid == empid).OrderByDescending(c => c.Applydate).Select(a => new {
                a.FlowId,
                a.FlowContent,
                a.States,

            }).Take(20).ToList();





            return Ok(wfs);
        
        }



        [HttpGet]
        public IActionResult MyApplydetail(string id)
        {
            //Int32 idd = Int32.Parse(id);
            //  var fs=db.WorkFlowsInstance.Join(db.EmEmpData,c=>c.ApproveUser,per=>per.)
            var fws = db.WorkFlowsInstance.Where(c => c.WorkFlowId == id).Join(db.EmEmpData, wf => wf.ApproveUser, em => em.EmpNo, (wf, em) => new
            {
                Id = wf.Id,
                ApproveUser = em.Fname,
                FlowStep = wf.FlowStep,
                ApproveDate = wf.ApproveDate,
                Commnet = wf.Commnet,
                Approved = wf.Approved,
                Refused = wf.Refused,
                WorkFlowId = wf.WorkFlowId,
                IsCurrentStep = wf.IsCurrentStep,
                LastStep = wf.LastStep,


            }).OrderBy(c => c.FlowStep).ToList();
            // return _context.Pets.Join(_context.Persons,pet=>pet.Owner,per=>per.Id,(pet,per)=>new PetsDetails
            return Ok(fws);
        }

        [HttpGet]
        public IActionResult lot(string id)
        {
            var ls = db.WorkFlowsInstance.Where(c => c.ApproveUser == id && c.IsCurrentStep == true).ToList();
            foreach (var itm in ls)
            {
                Approved(itm.Id.ToString());
            
            }



        return Ok(new { msg = "批量操作成功" });

        }

        public void token()
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.Appkey = "ding5ibuqempqoqfzykn";//"dingt691drnrkopwdusb";
            req.Appsecret = "fctZRJClnx8eFiWgEbzUfKWyldx82sZTXxeAg5HKqubvb64oMMjwtj6fJgO2rIRj";//"zIH8e2rQrPxDglVHy21VZXoU-Y9CjQ581QjhRm2eA40gfIBQey2tyyg-sLEnz09e";
            req.SetHttpMethod("GET");
            OapiGettokenResponse rsp = client.Execute(req, access_token);
            Console.WriteLine(rsp.Body);
            // return Ok(new {token=rsp.AccessToken });
            access_token = rsp.AccessToken;
        }
        [HttpGet]
        public ActionResult gettokenstr()
        {
            token();
            return Ok(new { token = access_token });
        }



        public ActionResult agree(string[] lst)
        {

            foreach (var item in lst)
            {
                Approved(item);
            }

            return Ok(new { msg="批量批准成功"});
        }

        public ActionResult disagree(string[] lst)
        {

            foreach (var item in lst)
            {
                Reject(item);
            }

            return Ok(new { msg = "批量拒绝成功" });
        }









        //获取Token缓存 数据，缓存token
        public string get_token()
        {
            var tokenstr = Cache.Get("token");
            if (tokenstr == null)
            {
                token();
                Cache.Set("token", access_token, TimeSpan.FromSeconds(7100));
                return access_token;
            }
            else
            {


                return tokenstr.ToString();

            }


        }





        //获取车辆列表

        public IActionResult GetCarList()
        {

            var ls = db.AppCar.ToList();

            return Ok(ls);

             
        
        }

      




    }






    public class Approve
    {
        public string content { get; set; }
        public int id { get; set; }
        public string type { get; set; }
        public string reson { get; set; }
        public string  caru { get; set; }

    }
}